package com.aiti.ai.task;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.aiti.ai.service.ShowPremuEnterpriseService;
import com.aiti.ai.service.ai.MessageAssistant;
import com.aiti.ai.tool.SearXNGWebSearchTool;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.service.AiServices;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;

/**
 * description:
 * auth fcb
 * date 2025-03-22 16:13
 **/
@Slf4j
public class MainTaskRunnable implements Runnable{

    private static final int DEFAULT_BATCH_SIZE = 1000;

    private ShowPremuEnterpriseService showPremuEnterpriseService;

    private int taskCount;

    private MessageAssistant newFieldAssistant;

    public MainTaskRunnable(ShowPremuEnterpriseService showPremuEnterpriseService, ChatLanguageModel model, SearXNGWebSearchTool searXNGWebSearchTool) {
        this.showPremuEnterpriseService = showPremuEnterpriseService;
        // 线程数量，每个CPU8个线程
        this.taskCount =  Runtime.getRuntime().availableProcessors() * 5;
        this.newFieldAssistant = AiServices.builder(MessageAssistant.class)
                .chatLanguageModel(model)
                .tools(searXNGWebSearchTool).build();
    }

    @Override
    public void run() {
        // 查询总数据条数或增量数据条数
        int sum = showPremuEnterpriseService.queryUnDealCount();
        //int sum = 3200;
        if(sum == 0) {
            log.info("【AI生成数据】没有数据要执行");
            return;
        }
        // 每个线程每次处理的数据量
        int threadDealCount = 40;
        // [500,1000]
        if(sum <= DEFAULT_BATCH_SIZE && sum  > (DEFAULT_BATCH_SIZE / 2)) {
            threadDealCount = 20;
        // (100. 500]
        } else if(sum <= (DEFAULT_BATCH_SIZE / 2) && sum > 100) {
            threadDealCount = 10;
        }else if(sum <= 100) {
            threadDealCount = 1;
        }
        // 主线程循环一次要处理的数量
        int pageSize = this.taskCount * threadDealCount;
        int loopCount = getLoopCount(sum, pageSize);
        try {
            for (int i = 1; i <= loopCount; i++) {
                CountDownLatch latch = new CountDownLatch(taskCount);
                for (int t = 1; t <= taskCount; t++) {
                    int limit = (t - 1) * threadDealCount;
                    int offset =  threadDealCount;
                    new Thread(new ExeTaskRunnable(latch, limit, offset, showPremuEnterpriseService, newFieldAssistant)).start();
                }
                latch.await();
            }
        }catch (Exception e) {
            log.error("【AI生成数据，主线程异常】:{}", ExceptionUtil.stacktraceToString(e));
        }
        log.warn("【AI生成数据】执行完毕");
    }

    /**
     * 计算循环次数
     * @param sum
     * @param pageSize
     * @return
     */
    private int getLoopCount(int sum, int pageSize) {
        int count = sum / pageSize;
        int size = pageSize * count;
        if(size < sum) {
            count++;
        }
        return count;
    }


}
